package com.group7d.fileparser;

import com.group7d.entity.TestResult;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;
import org.apache.commons.io.FileUtils;

/**
 * jtl文件解析器.
 *
 * @author jinshulin (jinshulin170531@credithc.com)
 * @version 0.0.1-SNAPSHOT
 * @since 2018年05月02日 21时42分
 */
public final class JtlFileParser {

    private static final String SEPARATOR = ",";

    /**
     * 解析jtl文件
     * @param jtlFile
     * @return
     * @throws IOException
     */
    public static List<TestResult> readFile(File jtlFile) throws IOException {
        checkFile(jtlFile);
        return getTestResults(jtlFile);
    }

    private static List<TestResult> getTestResults(File file) throws IOException {
        return FileUtils.readLines(file, "utf-8").stream()
            .map(
                line -> {
                    String[] cells = line.trim().split(SEPARATOR);
                    if (cells.length <= 0) {
                        return null;
                    }
                    return new TestResult(
                        Long.parseLong(cells[0]), cells[1],
                        cells[2], cells[3], cells[4], cells[5],
                        cells[6], cells[7], cells[8], Long.parseLong(cells[9]),
                        Long.parseLong(cells[10]), Integer.parseInt(cells[11]),
                        Integer.parseInt(cells[12]), cells[13],
                        cells[14], cells[15]
                    );
                }
            )
            .filter(result -> result != null)
            .collect(Collectors.toList());
    }

    /**
     * 检查文件是否有效
     * @param file
     */
    private static void checkFile(File file) {
        if (!file.exists() || !file.isFile() || !file.canRead()) {
            throw new IllegalArgumentException("Illegal File: " + file.getAbsolutePath());
        }
    }

}
